//
//  CommentListViewController.m
//  Cycling
//
//  Created by 迟国强 on 2023/4/19.
//

#import "CommentListViewController.h"
#import "CommentItemCell.h"
#import "RouteDetailModel.h"
#import "RouteRequest.h"
#import "CommentView.h"
@interface CommentListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger page;
@end

@implementation CommentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评论";
    self.page = 1;
    [self setUI];
    [self loadData];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadData];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self loadData];
    }];
    // Do any additional setup after loading the view.
}

- (void)loadData {
    [RouteRequest getCommentListWith:self.page pid:self.isSuper ? self.pid : self.commentPid isSuper:self.isSuper result:^(BOOL success, NSDictionary * _Nonnull data, NSString * _Nonnull reason) {
        if (success) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
            }
            NSArray *comments = data[@"comments"];
            for (int i = 0; i < comments.count; i++) {
                NSMutableDictionary *dic = comments[i];
                RouteCommentModel *model = [RouteCommentModel mj_objectWithKeyValues:dic];
                model.isSuper = YES;//是否是第一层
                [self.dataArr addObject:model];
                if (model.rec.count != 0) {
                    [self.dataArr addObjectsFromArray:model.rec];
                }
            }
        }
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [self.collectionView reloadData];
    }];
}

- (void)setUI {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = 0;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NavigationBarHeight, SCREEN_W, SCREEN_H - 50 - NavigationBarHeight - SafeAreaBottomHeight) collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.clearColor;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (@available(iOS 11.0, *)) {
        collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [collectionView registerNib:[UINib nibWithNibName:@"CommentItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"CommentItemCell"];

    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view).offset(NavigationBarHeight);
        make.bottom.equalTo(self.view.mas_bottom).offset(-SafeAreaBottomHeight - 50);
    }];
    
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commentBtn setTitle:@"评论" forState:UIControlStateNormal];
    commentBtn.backgroundColor = rgbHex(0x1ED6C2, 1);
    commentBtn.titleLabel.font = PingFangFont(14);
    commentBtn.layer.cornerRadius = 22;
    commentBtn.layer.masksToBounds = YES;
    [commentBtn addTarget:self action:@selector(comment) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:commentBtn];
    [commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(30);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.bottom.equalTo(self.view.mas_bottom).offset(-3 - SafeAreaBottomHeight);
        make.height.offset(44);

    }];
}

- (void)comment {
    [CommentView CommentWith:NSObject.getKeyWindowRootViewController Complection:^(NSString * _Nonnull content) {
        [RouteRequest commentsRouteWithRouteId:self.pid text:content recid:self.isSuper ? @"":self.commentPid result:^(BOOL success) {
            if (success) {
                [self showHudTipStr:@"评论成功"];
                self.page = 1;
                [self loadData];
            }
        }];
        [NSObject.getKeyWindowRootViewController gq_removeBgView];
    }];
}

#pragma collectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CommentItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CommentItemCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"CommentItemCell" owner:self options:nil] lastObject];
    }
    cell.model = self.dataArr[indexPath.row];
    cell.block = ^(RouteCommentModel * _Nonnull model) {
        [CommentView CommentWith:NSObject.getKeyWindowRootViewController Complection:^(NSString * _Nonnull content) {
            [self commentRouteWith:content commentId:model.id];
            [NSObject.getKeyWindowRootViewController gq_removeBgView];
        }];
    };
    cell.commentBtn.hidden = !self.isSuper;
    return cell;
}
- (void)commentRouteWith:(NSString *)text commentId:(NSString *)recid {
    [RouteRequest commentsRouteWithRouteId:self.pid text:text recid:self.isSuper ? @"":recid result:^(BOOL success) {
        if (success) {
            [self showHudTipStr:@"评论成功"];
            self.page = 1;
            [self loadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CommentSubNotification" object:nil];
        }
    }];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    RouteCommentModel *model = self.dataArr[indexPath.row];

    CGFloat h = 90;
    CGSize size = [model.content boundingRectWithSize:CGSizeMake(SCREEN_W-60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:PingFangFont(20)} context:nil].size;
    h += size.height;
    return CGSizeMake(SCREEN_W - 36, h);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
@end
